//使用vuex 三步 
// 第一步 引入 

import Vue from 'vue'
import Vuex from 'vuex'



import { getHomeData } from '../api/index'


// 第二步 挂载   

Vue.use(Vuex)

// 第三步导出  定义 vuex 的四个核心  

let state = {
    mgs: 'vuex',
    homeList:[],
    // totalPrice:0
}


let mutations = {

    homeData(state,data){
        // alert(1)
        console.log(data)
        state.homeList=data
    },

    delete(state,myid) {
        state.homeList.find((item,index)=>{
            if(item.id==myid) {
                state.homeList.splice(index,1)
            }
        })
    },

    reduceNum1(state,myid) {
    //   let everyData=  state.homeList.find((item,index)=>{
    //         if(item.id==myid) {
    //             return true
    //         }
    //     })

    //     console.log(everyData)

    //     everyData.count--;

    state.homeList.find((item,index)=>item.id==myid).count--;


    },

    addNum1(state,myid) {
        state.homeList.find((item,index)=>item.id==myid).count++;

    },
    updateHomList(state,data){
  

       let aaa=  state.homeList.map(item=>{
        

            if(item.id===data.id) {
                // console.log(  '以前:',item)
                let newstr=JSON.stringify(data);
                let str=JSON.stringify(item)
                str=newstr;
                // console.log('现在：',str)
                let newItem=JSON.parse(str);
                return newItem           
            }else {
                return    item
            }



           
        })

        console.log('aaa:',aaa);

        state.homeList=aaa;

       
       



        
    }


}

let getters = {
    totalPrice(state) {
     let  totals=state.homeList.reduce((acc,current)=>{
              return acc+current.count*current.price
          },0)

       return  totals


    // return   state.homeList.reduce((acc,current)=>acc+current.count*current.price,0)

    }


    
}


let actions = {

    getHomeData(context) {
        // alert(1)
        //发送axios 请求 

        let homeArr = []
        getHomeData().then(res => {
            //  console.log(res)
            res.map(item => {
                // console.log(item)
                item.date = new Date().toLocaleDateString()
                // console.log(item)
                homeArr.push(item)


            });  
            // console.log(homeArr)

            context.commit('homeData',homeArr)
        })

      
     

    },


    deleteId(context,id) {
        // console.log(id)
      context.commit('delete',id)  

    },
    reduceCount(context,id) {
        context.commit('reduceNum1',id)
    },

    addCount(context,id) {

        context.commit('addNum1',id)

    },

    updateData(context,data,callback){
       context.commit('updateHomList',data)
       callback&& callback()
    }
  

}



let store = new Vuex.Store({
    state,
    mutations,
    getters,
    actions
})


export default store

